/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.service;

import java.math.BigDecimal;
import java.util.List;
import server.constants.GlobalConstants;
import server.constants.ProductConstants;
import server.dao.ProductDAO;
import server.domain.Product;

/**
 *
 * @author fillipe
 */
public class ProductService {

    private ProductDAO productDAO;

    public ProductService() {
        this.productDAO = new ProductDAO();
    }

    public String insert(Product product) {
        try {
            if (product.getStock() < ProductConstants.STOCK_MIN) {
                return ProductConstants.NOT_SAVED_STOCK;
            }
            if (product.getPrice().compareTo(new BigDecimal(0)) < 0) {
                return ProductConstants.NOT_SAVED_PRICE_MIN_ZERO;
            }
            productDAO.save(product);
            return ProductConstants.SAVED;
        } catch (Exception ex) {
            return GlobalConstants.ERROR_SAVE;
        }
    }

    public String update(Product product) {
        try {
            if (product.getStock() < 0) {
                return ProductConstants.NOT_SAVED_STOCK_MIN_ZERO;
            }
            if (product.getPrice().compareTo(new BigDecimal(0)) < 0) {
                return ProductConstants.NOT_SAVED_PRICE_MIN_ZERO;
            }
            productDAO.update(product);
            return ProductConstants.UPDATED;
        } catch (Exception ex) {
            return GlobalConstants.ERROR_UPDATE;
        }
    }
    
    public String delete(Product product){
        try {
            if (getById(product.getId()) == null){
                return ProductConstants.PRODUCT_NOT_FOUND;
            }
            if(productDAO.existProductOrder(product.getId())){
                return ProductConstants.NOT_DELETED_EXIST_ORDER;
            }
            productDAO.delete(product);
            return ProductConstants.DELETED;
        } catch (Exception ex) {
            return GlobalConstants.ERROR_DELETE;
        }
    }

    public Product getById(long id) {
        try {
            return productDAO.getById(id);
        } catch (Exception ex) {
            return null;
        }
    }

    public List<Product> getByDescription(String desc) {
        try {
            return productDAO.getByDescription(desc);
        } catch (Exception ex) {
            return null;
        }
    }
}
